/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.filing;

import com.softwarecraftsmen.orogeny.filing.absolutePathMetaData.AbsolutePathMetaData;
import com.softwarecraftsmen.orogeny.filing.absolutePathMetaData.BestGuessDynamicAbsolutePathMetaData;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import static java.lang.String.format;
import static java.util.Locale.UK;

public abstract class AbstractAbsolutePath implements AbsolutePath
{
	public void setMetaData(final @NotNull AbsolutePathMetaData metaData)
	{
		if (!exists())
		{
			throw new IllegalStateException(format(UK, "%1$s does not exist", this));
		}
		final File ourFile = toFile();

		ourFile.setLastModified(metaData.modificationTimeInMillisecondsSince1970());

		final boolean setReadableOnOwnerOnly = metaData.ownerPermissions().canRead() != metaData.groupPermissions().canRead();
		ourFile.setReadable(metaData.ownerPermissions().canRead(), setReadableOnOwnerOnly);

		final boolean setWritableOnOwnerOnly = metaData.ownerPermissions().canWrite() != metaData.groupPermissions().canWrite();
		ourFile.setWritable(metaData.ownerPermissions().canWrite(), setWritableOnOwnerOnly);

		final boolean setExecutableOnOwnerOnly = metaData.ownerPermissions().canExecuteOrCanSearchInDirectory() != metaData.groupPermissions().canExecuteOrCanSearchInDirectory();
		ourFile.setExecutable(metaData.ownerPermissions().canExecuteOrCanSearchInDirectory(), setExecutableOnOwnerOnly);
	}

	@NotNull
	public BestGuessDynamicAbsolutePathMetaData dynamicMetaData()
	{
		return new BestGuessDynamicAbsolutePathMetaData(toFile());
	}
}
